package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName NioServer.java
 * @Description TODO
 * @createTime 2020年04月29日 13:54:00
 */
public class NioServer {
	private static Map<String, SocketChannel> clientMap = new HashMap<>();

	public static void main(String[] args) throws Exception {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.configureBlocking(false);
		ServerSocket socket = serverSocketChannel.socket();
		socket.bind(new InetSocketAddress(8899));
		Selector selector = Selector.open();
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		while (true) {
			try {
				selector.select();
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				Iterator<SelectionKey> iterator = selectionKeys.iterator();
				while (iterator.hasNext()) {
					SelectionKey selectionKey = iterator.next();
					final SocketChannel client;
					try {
						if (selectionKey.isAcceptable()) {
							ServerSocketChannel sever = (ServerSocketChannel) selectionKey.channel();
							client = sever.accept();
							client.configureBlocking(false);
							client.register(selector, SelectionKey.OP_READ);
							String key = "【" + UUID.randomUUID().toString() + "】";
							clientMap.put(key, client);
						} else if (selectionKey.isReadable()) {
							client = (SocketChannel) selectionKey.channel();
							ByteBuffer byteBuffer = ByteBuffer.allocate(512);
							int read = client.read(byteBuffer);
							if (read > 0) {
								byteBuffer.flip();
								Charset charset = StandardCharsets.UTF_8;
								String message = String.valueOf(charset.decode(byteBuffer).array());
								System.out.println(message);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					iterator.remove();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
